package com.zrc.module_my.fragment

import android.Manifest
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.gson.Gson
import com.zrc.superframe_aop.annotation.Permission
import com.zrc.superframe_base.ARouterHub
import com.zrc.superframe_base.mvx.mvc.BaseMvcFragment
import com.zrc.superframe_base.utils.transformations.GlideLoader
import com.zrc.module_my.IConstantPool
import com.zrc.module_my.MyApi
import com.zrc.module_my.R
import com.zrc.module_my.bean.DownListBean
import com.zrc.module_my.bean.DownloadData
import com.zrc.superframe_net.common.CacheConfig
import com.zrc.superframe_net.room.download.DownloadInfo
import com.zrc.superframe_net.room.download.DownloadState
import com.zrc.superframe_net.common.net.ApplySchedulers
import com.zrc.superframe_net.common.net.NetObserver
import com.zrc.superframe_net.common.net.Net
import com.zrc.superframe_net.common.net.NetCallBack
import com.zrc.superframe_net.common.download.NetDownloadCallBack
import com.zrc.superframe_net.common.download.NetDownloadManager
import com.zrc.superframe_ui.layout.SuperImageView
import com.zrc.superframe_ui.layout.SuperTextView
import jp.wasabeef.glide.transformations.RoundedCornersTransformation
import kotlinx.android.synthetic.main.fragment_down.*

/**
 * @Author: superman
 * @CreateTime: 6/27/21
 * @Describe:
 */
@Route(path = ARouterHub.FRAGMENT_DOWN, name = "下载案例")
class DownFragment : BaseMvcFragment(), NetDownloadCallBack {

    private lateinit var mCommonAdapter: DownListAdapter

    private var mRetrofitDownloadManager: NetDownloadManager? = null //下载管理

    override fun getLayoutID() = R.layout.fragment_down

    override fun initListener() {
        super.initListener()
        mCommonAdapter = DownListAdapter()
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = mCommonAdapter
        mRetrofitDownloadManager = NetDownloadManager(this)
        Net.getService(MyApi::class.java) //请求数据
            .getDownloadList(1, 1)
            .compose(ApplySchedulers<DownListBean>())
            .subscribe(
                NetObserver(
                    page = this,
                    cacheConfig = CacheConfig(
                        tag = IConstantPool.DOWNLOAD_URL + "/down_fragment",
                        cache = true,
                        cacheTime = 56000
                    ),
                    callback = object : NetCallBack<DownListBean>() {
                        override fun onSucceed(data: DownListBean, mothead: String) {
                            val list: List<DownloadData> = localList(data.list)//本地数据库缓存
                            mCommonAdapter.setList(list)
                            mRetrofitDownloadManager?.downloadAll(list.map { it.downInfo })//如果你需要，让默认等待的队列，开始下载，你就执行这句
                        }

                        @Throws
                        override fun onCookieSucceed(result: String?, mothead: String) {
                            super.onCookieSucceed(result, mothead)
                            val data: DownListBean =
                                Gson().fromJson(result, DownListBean::class.java)
                            onSucceed(data, mothead)

                        }
                    })
            )
    }

    override fun updateProgress(info: DownloadInfo, progress: Int) {
        val downloadData = queryDownloadData(info)
        downloadData?.let {
            it.downInfo.downState = DownloadState.DOWN.state
        }
        mCommonAdapter.notifyDataSetChanged()
    }

    override fun updateState(info: DownloadInfo, state: DownloadState) {
        val downloadData = queryDownloadData(info)
        downloadData?.let {
            it.downInfo.downState = state.state
        }
        mCommonAdapter.notifyDataSetChanged()
    }

    //查找 下载的对象对应List 列表的哪个数据，并刷新
    private fun queryDownloadData(info: DownloadInfo): DownloadData? {
        val data: List<DownloadData> = mCommonAdapter.data
        for (i in data.indices) {
            val downInfo = data[i].downInfo
            if (downInfo === info) {
                return data[i]
            }
        }
        return null
    }

    inner class DownListAdapter : BaseQuickAdapter<DownloadData, BaseViewHolder>(R.layout.fragment_download_list_item) {
        override fun convert(holder: BaseViewHolder, item: DownloadData) {
            holder.getView<TextView>(R.id.tv_name).text = item.name
            val iv_logo = holder.getView<SuperImageView>(R.id.iv_logo)
            GlideLoader.getInstance().displayRoundConnerImage(
                item.logo_url,
                iv_logo,
                R.drawable.fragmentation_help,
                6,
                RoundedCornersTransformation.CornerType.ALL
            )
            holder.getView<TextView>(R.id.tv_version_name).text = item.version_name
            holder.getView<TextView>(R.id.tv_size_fixed).text = "${item.size_fixed}"
            val progressBar = holder.getView<ProgressBar>(R.id.progressBar)
            progressBar.progress = item.progress
            progressBar.visibility = if (item.isShowProgress) View.VISIBLE else View.GONE
            val tv_down = holder.getView<SuperTextView>(R.id.tv_down)
            tv_down.text = item.stateText
            tv_down.setOnClickListener {
               down(item.downInfo)
            }
        }

        @Permission(
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CALL_PHONE
        )
        fun down(downInfo: DownloadInfo) {
            mRetrofitDownloadManager?.down(downInfo)
        }
    }

    //本地有缓存，那么直接从本地取，不重新下载
    fun localList(list: List<DownListBean.ListBean>): List<DownloadData> {
        return with(arrayListOf<DownloadData>()) {
            list.forEach {
                this.add(
                    DownloadData(//转换类，进行下载
                        it.logo_url,
                        it.name,
                        it.version_name,
                        it.size_fixed,
                        mRetrofitDownloadManager?.createDownInfo(url = it.down_url)//创建下载类，有判断缓存
                    )
                )
            }
            this
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mRetrofitDownloadManager?.destory()//切记要销毁，以免队列资源不回手
    }
}